import { Injectable } from '@angular/core';
import { AccessToken } from './token.type';
import { WebStorageUtils } from '../../util/web-storage.utils';
import { CookieService } from 'ngx-cookie';
import {
    ACCESS_TOKEN,
    EMPLOYEE_RESOURCES,
    EMPLOYEE_ROLE
} from '../../const/const';

/**
 * 基于Token认证，在前后端分离非常普通，本身只提供一个接口的形式展示如何优雅处理HTTP请求
 */
@Injectable()
export class TokenService {
    private _role: string[];
    private _resources: string[];

    set data(data: any) {
        const access_token = {
            access_token: data.access_token,
            refresh_token: data.refresh_token,
            expires_in: data.expires_in,
            scope: data.scope
        };

        // 加2000，以保证本地Token比服务器晚过期， 否则可能取回的Token的expires_in为0  (2019.1.24 需要每掉一次接口，重新刷新token失效时间，所以不再进行前端判断)
        // let expires = Date.now() + access_token.expires_in * 1000 + 2000;
        // this.cookieService.putObject(ACCESS_TOKEN, access_token, {
        //     expires: new Date(expires)
        // });
        this.cookieService.putObject(ACCESS_TOKEN, access_token);
        window['access_token'] = access_token.access_token;

        this._role = data.role;
        this._resources = data.resources;

        WebStorageUtils.set(EMPLOYEE_ROLE, this._role);
        WebStorageUtils.set(EMPLOYEE_RESOURCES, this._resources);
    }

    get access_token(): AccessToken {
        return (this.cookieService.getObject(ACCESS_TOKEN) ||
            {}) as AccessToken;
    }

    get role(): string[] {
        return this._role || WebStorageUtils.get(EMPLOYEE_ROLE) || [];
    }

    get resources(): string[] {
        return this._resources || WebStorageUtils.get(EMPLOYEE_RESOURCES) || [];
    }

    destroy() {
        this.cookieService.remove(ACCESS_TOKEN);
        WebStorageUtils.remove(EMPLOYEE_ROLE);
        WebStorageUtils.remove(EMPLOYEE_RESOURCES);
    }

    constructor(private cookieService: CookieService) {}
}
